import { useEffect, useState, useRef, Spin } from 'react';
import Map from '@/components/Map';
import { Input, InputNumber, Form, Button, Table, FloatButton,Space,Modal } from "antd";
import gcoord from 'gcoord'
import { PageContainer } from '@ant-design/pro-components'
import styles from './index.less'
import { routeDetail, routePointsUpdate } from '../service';
import { useCallbackState } from '@/hook/useCallbackState'
import { EditOutlined, SaveOutlined } from '@ant-design/icons'
import { calc } from 'antd/lib/theme/internal';
import { message } from 'antd';
import TOButton from "@/components/TableList/TOButton";
import { render } from '@testing-library/react';



const RouteMapMgr = ({
    record, closeDrawer
}) => {
    const map = useRef(null);
    const AMap = useRef(null);
    const startIcon = useRef(null);
    const endIcon = useRef(null);
    const polyline = useRef(null);
    const polylineEditor = useRef(null);
    const [selectRecord, setSelectRecord] = useState(null);
    const [dataSource, setDataSource] = useCallbackState([]);
    const [loading, setLoading] = useState(false);
    const [updateModalOpen, setUpdateModalOpen] = useState(false)
    const [updatePointForm] = Form.useForm();

    const onMapLoaded = (_map, _AMap) => {
        map.current = _map
        AMap.current = _AMap
        startIcon.current = new AMap.current.Icon({
            size: new AMap.current.Size(25, 34),
            image: '//a.amap.com/jsapi_demos/static/demo-center/icons/dir-marker.png',
            imageSize: new AMap.current.Size(135, 40),
            imageOffset: new AMap.current.Pixel(-9, -3)
        });
        endIcon.current = new AMap.current.Icon({
            size: new AMap.current.Size(25, 34),
            image: '//a.amap.com/jsapi_demos/static/demo-center/icons/dir-marker.png',
            imageSize: new AMap.current.Size(135, 40),
            imageOffset: new AMap.current.Pixel(-95, -3)
        });
        loadRouteInfo()
    };
    const loadRouteInfo = () => {
        let params = {
            id: record.id
        };
        setLoading(true)
        routeDetail(params).then(res => {
            let points = adjust(res.points ? res.points : [], 'down');
            points = gcoordConvert(points, gcoord.WGS84, gcoord.GCJ02)
            setDataSource(points, (items) => draw(items));
        }).finally(setLoading(false));
    }

    const gcoordConvert = (items, originGcoord, targetGcoord) => {
        if (!items) {
            return []
        }
        return items.map((item, i) => {
            let lnglat = gcoord.transform([item.longitude, item.latitude], originGcoord, targetGcoord);
            item.longitude = lnglat[0].toFixed(6);
            item.latitude = lnglat[1].toFixed(6)
            item.id = i;
            // const result = {
            //     id: i,
            //     longitude: lnglat[0].toFixed(6),
            //     latitude: lnglat[1].toFixed(6),
            // };
            return item
        })
    }

    const draw = (items) => {
        if (items?.length == 0) {
            return;
        }

        let path = items.map((item) => {
            return new AMap.current.LngLat(item.longitude, item.latitude)
        });
        polyline.current = new AMap.current.Polyline({
            path: path,
            borderWeight: 2,
            strokeColor: 'red',
            lineJoin: 'round'
        });
        map.current.clearMap();
        map.current.add(polyline.current);
        map.current.setFitView();
        drawMarker(startIcon.current, path[0])
        drawMarker(endIcon.current, path[path.length - 1])

    }

    const drawMarker = (icon, point) => {
        const marker = new AMap.current.Marker({
            position: point,
            icon: icon,
            offset: new AMap.current.Pixel(-13, -30)
        });
        map.current.add(marker)
        return marker
    }
    const openEditor = () => {
        polylineEditor.current = new AMap.current.PolylineEditor(map.current, polyline.current);
        polylineEditor.current.open();

    }
    const closeEditor = () => {
        if (!polylineEditor.current) return;
        polylineEditor.current.close()
        let path = polylineEditor.current.getTarget().getPath();
        let points = path.map((item) => {
            return {
                longitude: item.lng,
                latitude: item.lat,
            };
        });
        setDataSource(points)
    }
    const adjust = (items, dir) => {
        return items.map((item) => {
            let longitude = item.longitude;
            let latitude = item.latitude;
            if(dir == 'up'){
                longitude = Math.trunc(item.longitude * 1000000);
                latitude = Math.trunc(item.latitude * 1000000);
            }else{
                longitude = (item.longitude / 1000000).toFixed(6);
                latitude = (item.latitude / 1000000).toFixed(6);
            }
            item.longitude = longitude;
            item.latitude = latitude;
            return item;
        });
    }
    const saveRoutePoint = () => {
        let points = gcoordConvert(dataSource, gcoord.GCJ02, gcoord.WGS84);
        points = adjust(points, 'up');
        let data = {
            id: record.id,
            points: points,
        }
        routePointsUpdate(data).then(res => {
            closeDrawer()
        });
    }

    const delPoint = (record) => {
        let points = [...dataSource];
        points = points.filter(item => item.id !== record.id);
        setDataSource(points)
        draw(points)
    }
    const tableOnClick = (record) =>{
        setSelectRecord(record);
        map.current.setZoomAndCenter(
            8, new AMap.current.LngLat(record.longitude, record.latitude), true, 500
        )
    }
    const showUpdateModal = () => {
        setUpdateModalOpen(true)
    }
    const updateModalOnOk = () => {
        let valueMap = updatePointForm.getFieldsValue();
        updatePointForm.resetFields();
        let points = [...dataSource];
        points[valueMap.id] = valueMap;
        setDataSource(points);
        draw(points)
        setUpdateModalOpen(false)
    }
    const locationColumns = [{
        title: '序号',
        align: 'center',
        dataIndex: 'index',
        valueType: 'indexBorder',
        width: 60,
    },
    {
        title: '数据ID',
        dataIndex: "id",
        width: 120,
        hidden: true,
        key: "id"
    },
    {
        title: '经度',
        dataIndex: "longitude",
        width: 120,
    },
    {
        title: '纬度',
        dataIndex: 'latitude',
        width: 180,
    },
    {
        title: '速度(km/h)',
        dataIndex: 'velocity'
    },
    {
        title: '方向',
        dataIndex: 'dir',
    },
    {
        title: '操作',
        dataIndex: 'opt',
        render: (_, record) => (
            
            <Space size='middle'>
                <a
                    onClick={e => {
                        e.stopPropagation();
                        updatePointForm.setFieldsValue(record)
                        showUpdateModal()
                    }}
                >修改</a>
                <a
                    onClick={e => {
                        e.stopPropagation()
                        delPoint(record)
                    }}
                >
                    删除
                </a>
            </Space>
        )
    }
];
    return (
        <PageContainer className={styles.pageContainer}>
            <FloatButton.Group shape="circle" style={{ insetInlineEnd: 80, bottom: 500, position: 'absolute' }}>
                <FloatButton description='' type='primary' icon={<EditOutlined />} onClick={openEditor} />
                <FloatButton description='' type='primary' icon={<SaveOutlined />} onClick={closeEditor} />
            </FloatButton.Group>

            <div className={styles.container}>

                <div className={styles.mapWrap}>
                    <Map onMapLoaded={onMapLoaded}></Map>
                </div>

                <div className={styles.bottomInfos}>
                    <Table
                        dataSource={dataSource}
                        rowKey='id'
                        columns={locationColumns}
                        size='small'
                        onRow={(record) =>{
                            return {
                                onClick: (event) => {tableOnClick(record)}
                            }
                        }}
                        scroll={
                            {
                                scrollToFirstRowOnChange: true,
                                x: 200,
                                y: 140,
                            }
                        } />
                </div>
                <Button type="primary" size='large' onClick={saveRoutePoint}>保存</Button>
            </div>
            <Modal 
                title="修改位置点信息" 
                closable={{ 'aria-label': 'Custom Close Button' }}
                open={updateModalOpen} 
                onOk={updateModalOnOk}
                onCancel={() => {setUpdateModalOpen(false)}}
            >
                <Form form={updatePointForm}>
                    <Form.Item hidden={true} name="id">
                        <Input/>
                    </Form.Item>
                    <Form.Item name="longitude" label="经度">
                        <Input/>
                    </Form.Item>
                    <Form.Item name="latitude" label="纬度">
                        <Input/>
                    </Form.Item>
                    <Form.Item name="velocity" label="速度(km/h)">
                        <InputNumber/>
                    </Form.Item>
                    <Form.Item name="dir" label="方向">
                        <InputNumber/>
                    </Form.Item>
                </Form>
            </Modal>
        </PageContainer>

    );
}
export default RouteMapMgr;
